package org.demo.zookeeper;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;


public class Test {
	static CuratorFramework client = null;
	  
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		client = CuratorFrameworkFactory.builder()
				.connectString("192.168.70.30:2181") // 服务器列表
				.sessionTimeoutMs(5000) // 会话超时时间，单位毫秒
				.connectionTimeoutMs(3000) // 连接创建超时时间，单位毫秒
				.retryPolicy(new ExponentialBackoffRetry(1000, 3)) // 重试策略
				.build();
		
		client.start();

		String path = ZKUtil.normalize("/zk-test/znode");
		System.out.println(path);
		if (client.checkExists().forPath(path) == null) {
			client.create().creatingParentsIfNeeded()
					.withMode(CreateMode.PERSISTENT)
					.forPath(path, ZKUtil.toBytes("192.168.70.100"));

		}
		// client.setData().withVersion(-1).forPath(path,
		// ZKUtil.toBytes("192.168.70.101"));

		System.out.println(ZKUtil.toString(client.getData().forPath(path)));

		List<String> children = client.getChildren().forPath("/zk-test");

		System.out.println("Children: " + children);

		
		/**
	     * 监听数据节点的变化情况
	     */
	    final NodeCache nodeCache = new NodeCache(client, path, false);
	    nodeCache.start(true);
	    nodeCache.getListenable().addListener(
	      new NodeCacheListener() {
	        public void nodeChanged() throws Exception {
	          System.out.println("Node data is changed, new data: " + 
	            new String(nodeCache.getCurrentData().getData()));
	        }
	      }
	    );
	    
		/**
	     * 监听子节点的变化情况
	     */
	    final PathChildrenCache childrenCache = new PathChildrenCache(client, "/zk-test", true);
	    
	    childrenCache.start(StartMode.BUILD_INITIAL_CACHE);
	    childrenCache.getListenable().addListener(
	      new PathChildrenCacheListener() {
	        public void childEvent(CuratorFramework client, PathChildrenCacheEvent event)
	            throws Exception {
	            switch (event.getType()) {
	            case CHILD_ADDED:
	              System.out.println("CHILD_ADDED: " + event.getData().getPath());
	              break;
	            case CHILD_REMOVED:
	              System.out.println("CHILD_REMOVED: " + event.getData().getPath());
	              break;
	            case CHILD_UPDATED:
	              System.out.println("CHILD_UPDATED: " + event.getData().getPath());
	              break;
	            default:
	            System.out.println("default: " + event.getData().getPath());
	              break;
	          }
	        }
	      }
	    );
	    
//	    List<ChildData> datas = childrenCache.getCurrentData();
//
//	    for (ChildData data : datas) {
//	      System.out.println("pathcache:{" + data.getPath() + ":" + new String(data.getData())+"}");
//	    }
//	    Thread.sleep(1 * 1000);
//	    System.out.println("--------------------------");
//	    client.setData().forPath(path, "world".getBytes());
//	    
//	    Thread.sleep(1 * 1000);
//	    System.out.println("--------------------------");
//	    Stat stat = client.checkExists().forPath("/zk-test/znode-1"); 
//	    if(stat==null){
//	    	client.create().forPath("/zk-test/znode-1");
//	    }else{
//	    	client.delete().forPath("/zk-test/znode-1");
//	    }
//	    System.out.println("--------------------------");
//	    Thread.sleep(1 * 1000);
//	    
//	    
		nodeCache.close();
		childrenCache.close();
	    
		
//		DistributedLock distributedLock = new DistributedLock(client, "/zk-test/lock");
//		distributedLock.lock();
//		
//		Thread.sleep(2 * 1000);
//		distributedLock.unlock();
		
		 
		
		
		
		
		Thread.sleep(5 * 1000);
		 client.close();
	}
   
   
  }
	 
